package com.ziyun.erp.modules.message.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ziyun.erp.modules.message.dao.MessageDao;
import com.ziyun.erp.modules.message.entity.MessageEntity;
import com.ziyun.erp.modules.message.entity.MessageUserEntity;
import com.ziyun.erp.modules.message.service.MessageService;
import com.ziyun.erp.modules.message.service.MessageUserService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service("messageService")
@Transactional
public class MessageServiceImpl extends ServiceImpl<MessageDao, MessageEntity> implements MessageService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private MessageUserService messageUserService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<MessageEntity> page = this.selectPage(
                new Query<MessageEntity>(params).getPage(),
                new EntityWrapper<MessageEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 插入消息
     * @param message
     */
    @Override
    public void insertMessage(MessageEntity message) {
        //先插入消息表
        this.insert(message);

        //插入用户消息表 todo 后期可能改为根据消息类型推送给不同的用户
        List<Map<String, Object>> userList = sysUserService.selectMaps(
                                new EntityWrapper<SysUserEntity>()
                                .setSqlSelect("user_id as userId")
                                .eq("status","1")
                                );
        List<MessageUserEntity> messageUserEntityList = new ArrayList<>();
        for(Map map :userList){
            MessageUserEntity messageUserEntity = new MessageUserEntity();
            messageUserEntity.setMessageId(message.getId());
            messageUserEntity.setUserId(Integer.parseInt(map.get("userId").toString()));
            messageUserEntity.setDelFlag(0);
            messageUserEntity.setReadFlag(0);
            messageUserEntityList.add(messageUserEntity);
        }

        //批量插入
        this.messageUserService.insertBatch(messageUserEntityList);

    }

}
